<template>
    <div class="auth-page">
        <main class="auth-container">
            <form class="auth-form" @submit.prevent="handleSubmit">
                <h2>{{ $t('forgot_password.title') }}</h2>
                <!-- 手机号输入 -->
                <div class="form-group">
                    <div class="input-wrapper">
                        <img src="/icon/register/icon1.png" class="input-icon">
                        <input v-model="form.mobile" type="tel" placeholder="请输入手机号" maxlength="11"
                            @blur="validateField('mobile')">
                    </div>
                    <span v-if="errors.mobile" class="error">{{ errors.mobile }}</span>
                </div>
                <!-- 身份证验证 -->
                <div class="form-group">
                    <div class="input-wrapper">
                        <img src="/icon/register/icon3.png" class="input-icon">
                        <input v-model="form.card" type="text" placeholder="身份证后四位" maxlength="4"
                            @blur="validateField('card')">
                    </div>
                    <span v-if="errors.card" class="error">{{ errors.card }}</span>
                </div>

                <!-- 新密码输入 -->
                <div class="form-group">
                    <div class="input-wrapper">
                        <img src="/icon/register/icon2.png" class="input-icon">
                        <input v-model="form.newPassword" type="password" placeholder="请输入新密码（6-20位字母+数字）"
                            @blur="validateField('newPassword')">
                    </div>
                    <span v-if="errors.newPassword" class="error">{{ errors.newPassword }}</span>
                </div>

                <!-- 确认密码 -->
                <div class="form-group">
                    <div class="input-wrapper">
                        <img src="/icon/register/icon2.png" class="input-icon">
                        <input v-model="form.confirmPassword" type="password" placeholder="确认密码（6-20位字母+数字）"
                            @blur="validateField('confirmPassword')">
                    </div>
                    <span v-if="errors.confirmPassword" class="error">{{ errors.confirmPassword }}</span>
                </div>

                <button type="submit" class="submit-btn">
                    {{ $t('forgot_password.submit') }}
                </button>
                <div class="auth-footer">
                    <nuxt-link :to="localePath('/Login')">
                        {{ $t('forgot_password.back_login') }}
                    </nuxt-link>
                </div>
            </form>
        </main>
    </div>
</template>

<script setup>
import { reactive } from 'vue'
import { sm2 } from 'sm-crypto' // 添加sm-crypto导入
import Base64 from 'crypto-js/enc-base64';
import Hex from 'crypto-js/enc-hex';
const { $fetchGov } = useNuxtApp()
const router = useRouter()
const localePath = useLocalePath()

definePageMeta({
    layout: 'login-layout' // 使用 custom-layout.vue 作为布局
});

const { t } = useI18n()

const form = reactive({
    mobile: '',
    card: '',
    newPassword: '',
    confirmPassword: ''
})

const errors = reactive({
    mobile: '',
    card: '',
    newPassword: '',
    confirmPassword: ''
})

// 验证规则集合
const validators = {
    mobile: () => {
        if (!form.mobile) return '手机号不能为空'
        if (!/^1[3-9]\d{9}$/.test(form.mobile)) return '手机号格式不正确'
        return ''
    },
    card: () => {
        if (!form.card) return '身份证后四位不能为空'
        if (!/^\d{3}[0-9Xx]$/.test(form.card)) return '请输入3位数字+身份证末位（如X）'
        return ''
    },
    newPassword: () => {
        if (!form.newPassword) return '新密码不能为空'
        if (form.newPassword.length < 6 || form.newPassword.length > 20)
            return '新密码长度6-20位'
        if (!/^(?=.*[a-zA-Z])(?=.*\d).+$/.test(form.newPassword))
            return '需包含字母和数字'
        return ''
    },
    confirmPassword: () => {
        if (!form.confirmPassword) return '确认密码不能为空'
        if (form.confirmPassword !== form.newPassword) return '两次密码不一致'
        return ''
    }
}

// 单个字段验证
const validateField = (field) => {
    errors[field] = validators[field]()
}

// 提交验证
const validateAll = () => {
    return Object.keys(validators).every(field => {
        errors[field] = validators[field]()
        return !errors[field]
    })
}

const { data: sm2Key } = await useAsyncData(
    'sm2Key',
    () => $fetchGov('/app/api/env/client-public-key', {
        method: 'GET',
        params: {
            _t: Date.now()
        }
    })
)

const handleSubmit = async () => {
    if (!validateAll()) return
    if (!sm2Key.value?.data) {
        return
    }
    try {
        const encryptedPassword = Base64.stringify(Hex.parse('04' + sm2.doEncrypt(form.confirmPassword, sm2Key.value.data, 1)))
        const { data: responseData } = await $fetchGov('/app/api/user/app/api/reset-password', {
            method: 'PUT',
            body: {
                mobile: form.mobile,
                card: form.card,
                password: encryptedPassword
            }
        });
        if (responseData.status === 0) {
            ElMessage.success('重置密码成功')
            setTimeout(() => {
                router.push(
                    localePath({
                        path: `/Login`
                    })
                )
            }, 1000);
        } else {
            ElMessage.error(responseData.message)
        }
    } catch (err) {
        console.error('重置密码失败:', err)
    }
}
</script>

<style lang="scss" scoped>
@use '@/assets/scss/login/index' as *;

.form-container {
    //   @include form-container;
    max-width: 480px;

    .input-group {
        margin-bottom: 20px;

        label {
            //   @include form-label;
        }

        input {
            //   @include form-input;

            &[type="password"] {
                letter-spacing: 2px;
            }
        }
    }

    .submit-btn {
        // @include primary-button;
        width: 100%;
        margin-top: 15px;
    }

    .login-link {
        text-align: center;
        margin-top: 20px;

        a {
            color: $myprimary-color;
            font-size: 14px;
            text-decoration: none;

            &:hover {
                text-decoration: underline;
            }
        }
    }
}
</style>